import axios from 'axios'

import {
	handleRequestHeader,
	handleAuth,
	handleAuthError,
	handleGeneralError,
	handleNetworkError,
  handleConfig,
} from './tools'

const http = axios.create(handleConfig);
http.interceptors.request.use((config) => {
  config = handleRequestHeader(config)
	config = handleAuth(config)
  // console.log(config,"请求配置以及参数")
	return config
})

http.interceptors.response.use(
    (response) => {
        if (response.status !== 200) return Promise.reject(response.data)
        handleAuthError(response.data.code)
        handleGeneralError(response.data.code, response.data.msg)
        return response
    },
    (err) => {
        console.log(err.response.data)
        handleNetworkError(err.response.data.msg)
        return Promise.reject(err.response)
    }
)

export const Get =(url, params = {}, clearFn) =>
  new Promise((resolve) => {
    http
      .get(url, { params })
      .then((result) => {
        let res
        if (clearFn !== undefined) {
          res = clearFn(result.data)
        } else {
          res = result.data
        }
        resolve(res)
      })
      .catch((err) => {
        resolve([err, undefined])
      })
  })

export const Post =(url, data, params = {}) => {
  return new Promise((resolve) => {
    http
      .post(url, data, { params })
      .then((result) => {
        resolve(result.data)
      })
      .catch((err) => {
        resolve([err, undefined])
      })
  })
}

export const Put = (url,data,params = {}) => {
    return new Promise((resolve) => {
        http
            .put(url,data,{ params })
            .then((result) => {
                resolve(result.data)
            })
            .catch((error) => {
                resolve([error,undefined])
            })

    })
}

export const Delete = (url,params = {}) => {
    return new Promise((resolve) => {
        http
            .delete(url, {data: params})
            .then((result) => {
                resolve(result.data)
            })
            .catch((error) => {
                resolve([error,undefined])
            })

    })
}